<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="权限列表"
      :columns="columns"
      :pagination="false"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'/dept/add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增', { pid: '' })">
          新增权限
        </el-button>
        <el-button
          v-auth="'/dept/delete/*'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- icon -->
      <template #icon="scope">
        <el-icon v-if="scope.row.icon_name && scope.row.icon_type == 1" style="font-size: 18px">
          <component :is="scope.row.icon_name"></component>
        </el-icon>
        <i v-if="scope.row.icon_name && scope.row.icon_type == 2" class="iconfont" :class="scope.row.icon_name" />
      </template>
      <!-- sort -->
      <template #sort="scope">
        <el-input-number
          size="small"
          :min="0"
          :model-value="scope.row.sort"
          :disabled="!authButton('/dept/changeSort')"
          @change="(val: number) => changeSort(val, scope.row)"
        />
      </template>
      <!-- status -->
      <template #status="scope">
        <el-switch
          :model-value="scope.row.status"
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          :active-value="1"
          :inactive-value="0"
          :disabled="!authButton('/dept/change_status/*')"
          @click="changeStatus(scope.row)"
        />
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" v-auth="'/dept/edit/*'" @click="openDrawer('编辑', scope.row)"
          >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" v-auth="'/dept/delete/*'" @click="delAuth(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <AuthDrawer ref="drawerRef" />
  </div>
</template>

<script lang="ts">
export default {
  name: "authManage",
}
</script>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import AuthDrawer from "@/views/system/auth/AuthDrawer.vue";
import ProTable from "@/components/ProTable/index.vue";
import { onMounted, reactive, ref } from "vue";
import { auth } from "./auth.tsx";
import { ProTableInstance } from "@/components/ProTable/interface";
import {
  addAuthApi,
  changeStatusApi,
  authTreeApi,
  deleteAuthByIdApi,
  deleteAuthApi,
  editAuthApi,
  changeSortApi, authMenuApi
} from "@/api/modules/auth.ts";
import { useHandleData } from "@/hooks/useHandleData.ts";
import { authButton } from "@/hooks/useAuthButton.ts";
import {Recordable} from "@/interface/types.ts";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

const authMenus = ref<any[]>([]);

const { columns } = auth(authMenus.value);

// 获取分类树
onMounted(async () => {
  authMenuApi().then(res => {
    const data = res.data as any[];
    authMenus.value = data;
    proTable.value?.updateSearchColumn({ key: "pid", data: data });
  });
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return authTreeApi(newParams);
};

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return data;
};

// 打开 dialog(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<Recordable> = {}) => {
  console.log(rowData);
  let params = {
    title,
    rowData: { ...rowData },
    isView: title === "查看",
    authTree: authMenus.value,
    api: title === "新增" ? addAuthApi : title === "编辑" ? editAuthApi : "",
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value.acceptParams(params);
};

// 删除权限信息
const delAuth = async (row: Recordable) => {
  await useHandleData(deleteAuthByIdApi, row.id, `删除【${row.title}】权限`);
  proTable.value?.getTableList();
};

// 批量删除权限信息
const batchDelete = async (pds: string[]) => {
  await useHandleData(deleteAuthApi, { pds }, "删除所选权限信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 修改排序
const changeSort = async (val: number, row: Recordable) => {
  if (!authButton("/dept/changeSort")) {
    return;
  }
  await useHandleData(changeSortApi, { id: row.id, sort: val }, `修改【${row.title}】权限排序值`);
  proTable.value?.getTableList();
};

// 切换状态
const changeStatus = async (row: Recordable) => {
  if (!authButton("/dept/change_status/*")) {
    return;
  }
  await useHandleData(changeStatusApi, row.id, `切换【${row.title}】权限状态`);
  proTable.value?.getTableList();
};
</script>

<style scoped lang="scss"></style>
